package com.hmall.gateWay.filter;


import com.hmall.gateWay.config.AuthProperties;
import com.hmall.gateWay.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.function.Consumer;

@Component
@EnableConfigurationProperties(AuthProperties.class)
@RequiredArgsConstructor
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final AuthProperties properties;
    private final JwtTool jwtTool;
    //进行路径的匹配
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1、获取请求路径
        ServerHttpRequest request = exchange.getRequest();
        //2、判断是否要拦截
        if(isExclude(request.getPath().toString())){
            //说明是不需要拦截；则放行
            return chain.filter(exchange);
        }
        //3、如果要拦截，则需要去从请求头获取令牌Authorization并校验Authorization
        String token = request.getHeaders().getFirst("Authorization");
        try {
            Long userId = jwtTool.parseToken(token);
            //4、将用户信息传递到微服务
            System.out.println(" userId = " + userId);
            if (userId != null) {
                //将用户信息传递到下游微服务；通过请求头传递
                exchange.mutate().request(new Consumer<ServerHttpRequest.Builder>() {
                    @Override
                    public void accept(ServerHttpRequest.Builder builder) {
                        builder.header("user-info", userId.toString());
                    }
                }).build();
            }
        } catch (Exception e) {
            e.printStackTrace();
            //校验身份失败；返回401
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //5、放行
        return chain.filter(exchange);
    }

    private boolean isExclude(String path) {
        for (String excludePath : properties.getExcludePaths()) {
            if(antPathMatcher.match(excludePath,path)){
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
